package com.ttc.group2.videochat.activity;

import org.jivesoftware.smack.XMPPException;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.Toast;

import com.quickblox.chat.QBChatService;
import com.quickblox.users.model.QBUser;
import com.quickblox.videochat.core.QBVideoChatController;
import com.quickblox.videochat.model.listeners.OnQBVideoChatListener;
import com.quickblox.videochat.model.objects.CallState;
import com.quickblox.videochat.model.objects.VideoChatConfig;
import com.ttc.group2.videochat.R;
import com.ttc.group2.videochat.VideoChatApplication;
import com.ttc.group2.videochat.helper.DialogHelper;
import com.ttc.group2.videochat.interfaces.OnCallDialogListener;
import com.ttc.group2.videochat.utils.Const;
import com.ttc.group2.videochat.utils.DialogUtils;
import com.ttc.group2.videochat.view.BottomActionBar;
import com.ttc.group2.videochat.view.TitleBar;

public class ChatActivity extends BaseActivity implements OnClickListener {
	private static final String TAG = "ChatActivity";
	private ImageView imgBack, imgCancel;
	private TitleBar title, titleLand;
	private BottomActionBar bottombar;
	private QBUser opponentUser;
	private String user_name;
	private AlertDialog alertDialog;
	private VideoChatConfig videoChatConfig;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_conversation);

		initChatService();
		
		// get Opponent user_id from Intent
		int userId = getIntent().getIntExtra(Const.USER_ID, -1);
		user_name = getIntent().getStringExtra(Const.USER_NAME);

		opponentUser = new QBUser();
		opponentUser.setId(userId);
		opponentUser.setFullName(user_name);

		initView();

		// custom ActionBar
		customActionBar();

		// init VideoCall
		initVideoCall();

	}

	private void customActionBar() {
		mActionbar = getSupportActionBar();
		mActionbar.setDisplayShowHomeEnabled(false);
		mActionbar.setDisplayShowTitleEnabled(false);
		LayoutInflater inflater = LayoutInflater.from(this);
		View customView = inflater.inflate(R.layout.custom_actionbar, null);
		imgBack = (ImageView) customView.findViewById(R.id.custom_action_back);
		imgCancel = (ImageView) customView
				.findViewById(R.id.custom_action_cancel);

		title = (TitleBar) customView.findViewById(R.id.custom_title);
		titleLand = (TitleBar) customView
				.findViewById(R.id.custom_title_landscape);
		title.title.setText(user_name);
		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			titleLand = (TitleBar) findViewById(R.id.custom_title_landscape);
			titleLand.setVisibility(View.VISIBLE);
			title.setVisibility(View.GONE);
			titleLand.title.setText(user_name);
		}

		imgBack.setOnClickListener(this);
		imgCancel.setOnClickListener(this);

		mActionbar.setCustomView(customView);
		mActionbar.setDisplayShowCustomEnabled(true);
	}

	private void initView() {
		bottombar = (BottomActionBar) findViewById(R.id.chat_bottombar);
		bottombar.action_bar_call.setVisibility(View.VISIBLE);
		bottombar.actionbar_video_call.setVisibility(View.VISIBLE);
		bottombar.imgAction.setOnClickListener(this);
		bottombar.action_bar_call.setOnClickListener(this);
		bottombar.actionbar_video_call.setOnClickListener(this);
	}

	private void showPopupAction() {
		PopupMenu popUp = new PopupMenu(this, bottombar.imgAction);
		popUp.getMenuInflater().inflate(R.menu.main_menu, popUp.getMenu());
		popUp.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				DialogUtils.showToast(getApplicationContext(),
						"Click " + item.getTitle(), Toast.LENGTH_SHORT);
				return true;
			}
		});
		popUp.show();
	}
	

	private void initChatService() {
		if (!QBChatService.isInitialized()) {
			QBChatService.init(this);
		} else {
			Log.d("ActivityLogin", "InitChat not needed");
		}
	}

	// VideoCall Settings
	private void initVideoCall() {
		final VideoChatApplication app = (VideoChatApplication) getApplication();

		// VideoChat settings
		videoChatConfig = getIntent().getParcelableExtra(
				VideoChatConfig.class.getCanonicalName());

		// Set video chat listener
		try {
			QBVideoChatController.getInstance().setQBVideoChatListener(
					app.getCurrentUser(), qbVideoChatListener);
		} catch (XMPPException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.custom_action_back:
			finish();
			break;
		case R.id.custom_action_cancel:
			finish();
			break;
		case R.id.action_bar_call:
			// voice call activity
			break;
		case R.id.actionbar_video:
			// video call activity
			startVideoCallActivity();
			break;
		case R.id.action_icon:
			showPopupAction();
			break;
		default:
			break;
		}
	}

	private void startVideoCallActivity() {
		Intent intent = new Intent(this, VideoCallActivity.class);
		intent.putExtra(Const.USER_ID, opponentUser.getId());
		intent.putExtra(VideoChatConfig.class.getCanonicalName(),
				videoChatConfig);
		startActivity(intent);
	}

	// Set QBChat Listener
	OnQBVideoChatListener qbVideoChatListener = new OnQBVideoChatListener() {

		@Override
		public void onVideoChatStateChange(CallState callState,
				VideoChatConfig receivedVideoChatConfig) {
			videoChatConfig = receivedVideoChatConfig;

			switch (callState) {
			case ACCEPT:
				// show incoming dialog
				showIncomingCallDialog();
				break;
			case ON_ACCEPT_BY_USER:
				QBVideoChatController.getInstance().onAcceptFriendCall(
						videoChatConfig, null);
				startVideoCallActivity();
				break;
			case ON_REJECTED_BY_USER:
				DialogUtils.showToast(ChatActivity.this,
						getString(R.string.on_did_not_answer),
						Toast.LENGTH_SHORT);
				break;
			case ON_DID_NOT_ANSWERED:
				DialogUtils.showToast(ChatActivity.this,
						getString(R.string.on_reject_by_user),
						Toast.LENGTH_SHORT);
				break;
			default:
				break;
			}
		}
	};

	private Handler autoCancelHandler = new Handler(Looper.getMainLooper());
	private Runnable autoCancelTask = new Runnable() {

		@Override
		public void run() {
			if (alertDialog != null && alertDialog.isShowing()) {
				alertDialog.dismiss();
			}
		}
	};

	private void showIncomingCallDialog() {
		alertDialog = DialogHelper.showCallDialog(this,
				new OnCallDialogListener() {

					@Override
					public void onRejectCallClick() {
						QBVideoChatController.getInstance().acceptCallByFriend(
								videoChatConfig, null);
						autoCancelHandler.removeCallbacks(autoCancelTask);
					}

					@Override
					public void onAcceptCallClick() {
						QBVideoChatController.getInstance().acceptCallByFriend(
								videoChatConfig, null);
						startVideoCallActivity();
						autoCancelHandler.removeCallbacks(autoCancelTask);
					}
				});

		autoCancelHandler.postDelayed(autoCancelTask, 30000);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			toggleActionBar();
		}
		return super.onTouchEvent(event);
	}

	private void toggleActionBar() {
		if (mActionbar != null) {
			if (mActionbar.isShowing()) {
				mActionbar.hide();
			} else {
				mActionbar.show();
			}
		}
	}
}
